/*
 * 描述： Table信息Helper
 * 修改人： Weng.weng
 * 修改时间： 2021年6月11日
 * 项目： code-generator
 */
package com.tuozixuan.code.core;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.plugin.logging.Log;

import com.tuozixuan.code.jdbc.JdbcContext;
import com.tuozixuan.code.model.DbField;
import com.tuozixuan.code.model.Table;

import cn.hutool.json.JSONUtil;

/**
 * Table信息Helper<br>
 * 
 * @author Weng.weng
 * @version [版本号, 2021年6月11日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class TableInfoHelper {
    
	private JdbcContext jdbcContext;
	
	private Log log;
	
	public TableInfoHelper(JdbcContext jdbcContext, Log log) {
		this.jdbcContext = jdbcContext;
		this.log = log;
	}
	
	/**
	 * 
	 * 獲取指定數據庫表的相關信息<br>
	 *
	 * @param dbName 數據庫名
	 * @param tableName 表明
	 * @return Table 表信息
	 * @version [版本号, Jun 11, 2021]
	 * @author Weng.weng
	 */
	public Table getTableInfo(String dbName, String tableName) {

		log.debug("Obtaining Meta Information. dbName:" + dbName + " tableName:" + tableName);
		Table table = null;
		ResultSet tabs;
		try {
			DatabaseMetaData dbMetaData = jdbcContext.getConnection().getMetaData();
			String[] types = { "TABLE" };
			tabs = dbMetaData.getTables(null, dbName, tableName, types);
			while (tabs.next()) {
				String tableRemarks = tabs.getString("REMARKS");
				log.info("tableName:" + tableName +  " tableRemarks:" + tableRemarks);

				ResultSet resultSet = dbMetaData.getColumns(null, dbName, tableName, null);
				List<DbField> fieldList = this.buildFieldList(resultSet);

				table = new Table();
				table.setName(tableName);
				table.setComment(tableRemarks);
				table.setFieldList(fieldList);
			}
		} catch (Exception e) {
			log.error("獲取表信息異常", e);
		    throw new RuntimeException("獲取表信息異常", e);
		}
		
		log.debug("Obtaining Meta Information. table:" + JSONUtil.toJsonStr(table));
		return table;
	}

	/**
	 * 
	 * 從結果集中獲取表中的字段信息<br>
	 *
	 * @param resultSet 結果集
	 * @return List<DbField> 字段信息列表
	 * @version [版本号, Jun 11, 2021]
	 * @author Weng.weng
	 */
	private List<DbField> buildFieldList(ResultSet resultSet) throws SQLException {
		List<DbField> fieldList = new ArrayList<>();
		DbField field = null;
		while (resultSet.next()) {
			field = new DbField();
			field.setName(resultSet.getString("COLUMN_NAME"));
			field.setType(resultSet.getString("TYPE_NAME"));
			field.setComment(resultSet.getString("REMARKS"));
			log.debug(field.getName() + " " + field.getType() + " " + field.getComment());
			fieldList.add(field);
		}
		return fieldList;
	}

}
